<template>
  <div>
    <el-container>
      <el-header class="inside-header">
        <div  >
          <!-- 面包屑 -->
          <el-breadcrumb separator=">">
            <el-breadcrumb-item>基础数据</el-breadcrumb-item>
            <el-breadcrumb-item class="breadcrumbColor">黑名单</el-breadcrumb-item>
          </el-breadcrumb>
        </div>
      </el-header>
      <el-main>
        <div>
          <el-row style="height: 40px">
              <el-col :span="5" style="margin-left: 20px">
              <el-form-item label="开始时间" size="small">
                <el-date-picker clearable v-model="formData.startDateTime" style="width: 100%" type="datetime"  placeholder="请选择开始时间"/>
              </el-form-item>
            </el-col>
            <span>-</span>
            <el-col :span="4">
              <el-form-item label="" size="small">
                <el-date-picker clearable v-model="formData.endDateTime" style="width: 92%" type="datetime"  placeholder="请选择结束时间"/>
              </el-form-item>
            </el-col>
            <el-col :span="4" style="margin-left: 5px">
              <el-form-item label="车牌号" size="small">
                <el-input clearable v-model="formData.cl_cph" maxLength="8" placeholder="请输入车牌号" />
              </el-form-item>
            </el-col>
            <el-col :span="4" style="margin-left: 20px">
              <el-button size="small" class="sele-but" icon="search" @click="selectQuery">查询</el-button>
              <el-button size="small" class="empty-but" icon="refresh" @click="onReset">重置</el-button>
            </el-col>
          </el-row>
        </div>
         <div style="height: 45px; display: flex; align-items: center;background:#f2f4f5;margin-left:-20px;margin-right:-19.5px">
          <el-button size="small" icon="plus" class="add-but" @click="addDialog = true" style="margin-left:20px">新增</el-button>
           <el-button type="danger" plain size="small" icon="delete" @click="deleteAll">删除</el-button>
          <el-button size="small" class="empty-but" icon="upload" @click="dialogTableVisible = true">导入</el-button>
          <el-button size="small" icon="download" class="empty-but" @click="exportExcelData(formData)">导出</el-button>
        </div>
        <div style="background: #fff">
          <el-table :data="tableData" style="width: 100%" height="460"  @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column align="center" type="index" prop="id" label="序号" width="50px" show-overflow-tooltip/>
            <el-table-column align="center" prop="cl_cph" label="车牌号" width="80px" show-overflow-tooltip/>
            <el-table-column align="center" prop="blacklistCause" width="180px" label="黑名单原因" show-overflow-tooltip/>
            <el-table-column align="center" prop="startDateTime" width="180px" label="开始时间" show-overflow-tooltip/>
            <el-table-column align="center" prop="endDateTime" width="180px" label="结束时间" show-overflow-tooltip/>
            <el-table-column align="center" prop="black_state" label="状态" width="60px" show-overflow-tooltip>
            <template #default="scope">
               <el-button link v-if="scope.row.black_state== 0"  size="small" type="danger" >禁用</el-button>
               <el-button link  v-if="scope.row.black_state== 1" size="small" type="success" >启用</el-button>
            </template>
          </el-table-column>
            <el-table-column align="center" prop="creationPerson" label="创建人" />
            <el-table-column align="center" prop="creationTime" label="创建时间" width="180px"
             :formatter="function(row,column){ if(row.creationTime){ return $moment(row.creationTime).format('YYYY-MM-DD HH:mm:ss')  }else{  return '' }}" />
              <el-table-column align="center" fixed="right" label="操作"  width="200" >
              <template #default="scope">
                <el-button link v-if="scope.row.black_state== 1" size="small" icon="close" @click="forbiddenRow(scope.row.blacklist_id)" type="danger">禁用</el-button>
                <el-button link  v-if="scope.row.black_state== 0" size="small" icon="check" @click="openRow(scope.row.blacklist_id)" type="success">启用</el-button>
                <el-button link   type="primary"  icon="edit"   size="small"  @click="updateDetail(scope.row)">修改</el-button>
                <!--<el-button link   type="danger"  icon="delete" size="small"     @click="deleteRow(scope.row)" >删除</el-button >-->
              </template>
            </el-table-column>
          </el-table>
          <el-pagination style="margin-right:40px; display: flex; justify-content: flex-end"  v-model:current-page="queryInfo.pagenum" v-model:page-size="queryInfo.pagesize"
                         size="small"  layout="prev, pager, next, jumper,total"
                   :total="queryInfo.total" @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
        </div>
      </el-main>
    </el-container>
<!--新增弹出框-->
<el-dialog v-model="addDialog" title="新增黑名单" width="40%">
    <div style="width: 80%">
        <el-form  ref="ruleFormRef" :model="form" status-icon :rules="rules" label-width="120px" class="demo-ruleForm">
            <el-form-item label="车牌号" prop="cl_cph">
                <el-input  clearable v-model="form.cl_cph" placeholder="请输入" autocomplete="off" />
            </el-form-item>
             <el-form-item label="开始时间" prop="startDateTime">
                <el-date-picker clearable v-model="form.startDateTime" type="datetime"  placeholder="请选择开始时间"/>
            </el-form-item>
             <el-form-item label="结束时间" prop="endDateTime">
                <el-date-picker clearable v-model="form.endDateTime" type="datetime"  placeholder="请选择结束时间"/>
            </el-form-item>
            <el-form-item label="黑名单原因" prop="blacklistCause">
                <el-input clearable v-model="form.blacklistCause" maxlength="500" placeholder="请输入" show-word-limit type="textarea" />
            </el-form-item>
        </el-form>
    </div>
    <template #footer>
        <span class="dialog-footer">
          <el-button class="sele-but" @click="add(form)"> 确定 </el-button>
          <el-button class="empty-but" @click="close">取消</el-button>
        </span>
      </template>
</el-dialog>
<!--修改弹出框-->
<el-dialog v-model="updateDialog" title="修改黑名单" width="40%">
    <div style="width: 80%">
        <el-form  ref="ruleFormRefUpdate" :model="obj" status-icon :rules="rules" label-width="120px" class="demo-ruleForm">
            <el-form-item label="车牌号" prop="cl_cph">
                <el-input clearable v-model="obj.cl_cph" placeholder="请输入" autocomplete="off" />
            </el-form-item>
             <el-form-item label="开始时间" prop="startDateTime">
                <el-date-picker clearable v-model="obj.startDateTime" type="datetime"  placeholder="请选择开始时间"/>
            </el-form-item>
             <el-form-item label="结束时间" prop="endDateTime">
                <el-date-picker clearable v-model="obj.endDateTime" type="datetime"  placeholder="请选择结束时间"/>
            </el-form-item>
            <el-form-item label="黑名单原因" prop="blacklistCause">
                <el-input clearable v-model="obj.blacklistCause" maxlength="500" placeholder="请输入" show-word-limit type="textarea" />
            </el-form-item>
        </el-form>
    </div>
    <template #footer>
        <span class="dialog-footer">
          <el-button class="sele-but" @click="update(obj)"> 确定 </el-button>
          <el-button class="empty-but" @click="updateDialog = false">取消</el-button>
        </span>
      </template>
</el-dialog>
      <!-- 导入弹出框 -->
<el-dialog style="width: 600px" v-model="dialogTableVisible" center title="导入文件">
          <div class="upload-demo">
            <el-upload ref="uploadFile" :file-list="state.fileList" action='#' accept=".xls" drag :http-request="uploadAction"
                :on-exceed="handleExceed" :limit="1" :show-file-list="false" :auto-upload="true" :before-upload="beforeUpload" style="width: 100%;">
              <el-icon class="el-icon--upload">
                <upload-filled />
              </el-icon>
              <div class="el-upload__text">
                将文件托到此处或<em>点击导入</em>
              </div>
              <template #tip>
                <div style="text-align:center;margin-top:10px">
               <p style="font-size:14px;">支持上传xsl格式文件,如果没有模板
               <a style="text-decoration:none;" href="template/黑名单导入模板.xls" download>
               <el-button link  type="primary" size="mini">点击下载</el-button></a>>
              </p>
              </div>
              </template>
            </el-upload>
          </div>
        </el-dialog>
  </div>
</template>

<script setup>
import {onMounted, reactive, ref} from "vue";
import {useRouter,useRoute} from "vue-router";
import { uploadExcel  } from "@/api/mobilePollution";
// 文件导入
import { ElMessage, ElMessageBox } from "element-plus";
import { selectAllBlackList,insertBlackList,updateBlackList,dleteBlackList,uploadBlackList,dleteAllBlackList } from"@/api/BasicAccessAudit"
import { blackListOut } from "@/api/leadingOut"
import * as XLSX from 'xlsx'
import moment from 'moment'
const router = useRouter()
const route = useRoute();
const tableData = ref([]);
const form = reactive({})
onMounted(()=>{
  selectQuery()
  let CPH = localStorage.getItem("blackListCph");
  if(CPH){
    form.cl_cph = reactive(JSON.parse(CPH));
    addDialog.value = true
  }else{

  }
})
const multipleSelection = ref([])
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}
const deleteAll = () => {
  if (multipleSelection.value.length == 0){
    ElMessage.error("请选择要删除的数据")
  }else {
    ElMessageBox.confirm("确定要删除吗?").then(()=>{
      dleteAllBlackList(multipleSelection.value).then((res) => {
        if(res.code == 200){
          ElMessage.success("删除成功!")
          selectQuery()
        }else {
          ElMessage.error('删除失败')
        }

      })
    })
  }
}
//查询所有
// const selectAll = () => {
//   selectAllBlackList({pageNum:1,pageSize:10}).then((res) => {
//     tableData.value = res.data.list
//     queryInfo.total=res.data.total;
//     // if (res.code == 200) {
//     //   tableData.value = res.data.list;
//     // } else {
//     //   ElMessage.error("查询失败!")
//     // }
//   });
// };
//搜索查询
const formData = reactive({})
const selectQuery = () => {
  if (formData.startDateTime){
    let startDate = moment(formData.startDateTime).format('YYYY-MM-DD HH:mm:ss')
    formData.startDateTime = startDate
  }
  if(formData.endDateTime){
    let endDate = moment(formData.endDateTime).format('YYYY-MM-DD HH:mm:ss')
    formData.endDateTime = endDate
  }
  formData.pageSize = queryInfo.pagesize
  formData.pageNum = queryInfo.pagenum
  selectAllBlackList(formData).then((res) => {
    if (res.code == 200) {
      tableData.value = res.data.list;
      queryInfo.total = res.data.total;
    } else {

    }

  });
};
//关闭
const close = () => {
  localStorage.removeItem("blackListCph");
  form.cl_cph = ""
  form.startDateTime = ""
  form.endDateTime = ""
  form.blacklistCause = ""
  addDialog.value = false
}
//分页
const queryInfo = reactive({
  pagenum:1,
  pagesize:10,
  total:0
})
const handleSizeChange = (val) => {
  queryInfo.pagesize = val
  selectQuery()
}
//点击第几页
const handleCurrentChange = (val) => {
  queryInfo.pagenum = val
  selectQuery()
}
// 重置
const onReset = () => {
  formData.startDateTime = "";
  formData.endDateTime = "";
  formData.cl_cph="";
  queryInfo.pagesize='10';
  queryInfo.pagenum = '1';
  localStorage.removeItem("blackListCph");
  selectQuery()
};
//开始时间小于结束时间
const validateTime =() =>{
  return (rule,value,callback)=>{
    if(form.endDateTime&&form.startDateTime&&form.endDateTime<form.startDateTime ||
        obj.endDateTime&&obj.startDateTime&&obj.endDateTime<obj.startDateTime){
      callback(new Error("开始时间要早于结束时间."))
    }else{
      callback();
    }
  }
}
// 校验
const rules = {
  cl_cph: [{
      required: true,
      message: "请填写车牌号",
      trigger: "blur",
    },
    {
      max:8,
      message:'车牌号最大长度为8位',
      trigger:'blur'
    },
    {
    pattern: /^([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[a-zA-Z](([DF]((?![IO])[a-zA-Z0-9](?![IO]))[0-9]{4})|([0-9]{5}[DF]))|[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1})$/,
    message:'请填写正确的车牌号',
    trigger: 'blur'
  }],
  startDateTime: [{
    required: true,
    validator:validateTime(),
    trigger: "change",
  }],
  endDateTime: [{
    required: true,
    validator:validateTime(),
    trigger: "change",
  }],
  blacklistCause: [{
    required: true,
    message: "请填写黑名单原因",
    trigger: "blur",
  }]
};
const clearForm = () => {
  form.cl_cph=""
  form.startDateTime =""
  form.endDateTime=""
  form.blacklistCause=""
}
//新增弹窗
const addDialog = ref(false);
const ruleFormRef = ref()
const add  = (form) => {
  if (!form) return
  ruleFormRef.value.validate(valid=>{
    if (valid) {
        form.startDateTime = moment(form.startDateTime).format('YYYY-MM-DD HH:mm:ss')
        form.endDateTime = moment(form.endDateTime).format('YYYY-MM-DD HH:mm:ss')
        form.creationPerson = localStorage.getItem('number')
        insertBlackList(form).then((res)=>{
          if (res.code == 200){
            ElMessage.success("新增成功!")
            addDialog.value = false
            localStorage.removeItem("blackListCph");
            clearForm()
            selectQuery()
          }else {
            ElMessage.error("新增失败!")
          }
        })
    } else {
    ElMessage.error("请填写必填项")
  }
})
    }

//修改禁行状态 --禁用
const forbiddenRow= (index) => {
  ElMessageBox.confirm("确定要禁行该车辆吗?").then(()=>{
    updateBlackList({blacklist_id:index,black_state:"0"}).then((res)=>{
      selectQuery()
    })
  })
}
//修改禁行状态 --启用
const openRow= (index) => {
  ElMessageBox.confirm("确定要启用该车辆吗?").then(()=>{
    updateBlackList({blacklist_id:index,black_state:"1"}).then((res)=>{
      selectQuery()
    })
  })
}
//修改
const ruleFormRefUpdate = ref()
const updateDialog = ref(false)
let obj = reactive({
  cl_cph:"",
  blacklistCause:""
})
const updateDetail = (row) => {
  updateDialog.value = true
  obj.blacklist_id = row.blacklist_id;
  console.log(row.id,'row.id',obj.id,'ssssss')
  obj.cl_cph = row.cl_cph;
  obj.blacklistCause = row.blacklistCause
  obj.startDateTime=row.startDateTime
  obj.endDateTime = row.endDateTime
}
const update = (row) => {
  console.log(row,'row')
  if (!row) return
  ruleFormRefUpdate.value.validate(valid => {
    if (valid) {
      row.startDateTime = moment(obj.startDateTime).format('YYYY-MM-DD HH:mm:ss')
      row.endDateTime = moment(obj.endDateTime).format('YYYY-MM-DD HH:mm:ss')
      updateBlackList(row).then((res) => {
        if (res.code == 200) {
          ElMessage.success("修改成功!")
          updateDialog.value = false
          selectQuery()
        } else {
          ElMessage.error("修改失败!")
        }
      })
    } else {
      ElMessage.error("请填写必填校验")
    }
  })
}
//删除
const deleteRow = (row) => {
  ElMessageBox.confirm("确定要删除吗?").then(()=>{
    dleteBlackList(row).then((res)=>{
      selectQuery()
    })
  })
}
//导入事件
const uploadFile = ref();
const dialogTableVisible = ref(false);
const state = reactive({
  bannerUrl: '',
  fileList: [],
  fileName: '',
})

const handleExceed = (files, fileList) => {
  if (state.fileList.length >= 1) {
    ElMessage.error('只能上传一个图片')
    return;
  }
}

const beforeUpload = (file) => {
  // const type = ['image/jpeg', 'image/jpg', 'image/png']
  // const type = ['application/vnd.ms-excel']
  // if (type.indexOf(file.type) === -1) {
  //   // ElMessage.error('上传的文件必须是JPG、JPEG、PNG三种之一!')
  //   ElMessage.error('上传的文件必须是xls,xlsx')
  //   return false
  // } else if (file.size / 1024 / 1024 > 2) {
  //   ElMessage.error('图片大小不能超过2MB!')
  //   return false
  // }
}

const uploadAction = (option) => {
  let param = new FormData();
  param.append('multipartFile', option.file);
  uploadBlackList(param).then((res) => {
    if (res.code === 200) {
      state.fileList = []
      dialogTableVisible.value = false
      ElMessage.success(res.data);
      selectQuery()
    }else if(res.code == 701){
      state.fileList = []
      dialogTableVisible.value = false
      ElMessage.error(res.data)
    }else if(res.code == 605){
      state.fileList = []
      dialogTableVisible.value = false
      ElMessage.error(res.data)
    }else{
      state.fileList = []
      dialogTableVisible.value = false
      ElMessage.error('文件导入失败')
    }
  }).catch(error => {
    state.fileList = []
    dialogTableVisible.value = false
    ElMessage.error('文件导入失败')
  });
}
//导出事件
let table = reactive({
  rows: [],
  total: 0
});
//黑名单导出 数据库字段表头(英文状态)
// const exportExcel = ()=>{
//   const data = XLSX.utils.json_to_sheet(tableData.value)//此处tableData.value为表格的数据
//   const wb = XLSX.utils.book_new()
//   XLSX.utils.book_append_sheet(wb,data,'test-data')//test-data为自定义的sheet表名
//   XLSX.writeFile(wb,'黑名单.xlsx')//test.xlsx为自定义的文件名
// }
//导出工序(中文)
const out = ref()
const exportExcelData = (formData) => {
  ElMessageBox.confirm("确定要导出数据吗?").then(()=>{
      blackListOut(formData).then((res)=>{
        if (res.data.length == 0){
          ElMessage.error("未查询到数据")
        }else {
          out.value = res.data
          exportExcel()
        }
      })
  })
}
const exportExcel = (formData) => {


    let exportData = []
    //导出数据结构构造
    out.value.forEach(item => {
      item.black_state = item.black_state == '0'?'禁用':'启用'
      exportData.push({
        cl_cph: item.cl_cph? item.cl_cph : '',
        blacklistCause: item.blacklistCause ? item.blacklistCause : '',
        startDateTime: item.startDateTime ? item.startDateTime : '',
        endDateTime:item.endDateTime ? item.endDateTime: '',
        black_state:item.black_state ? item.black_state: '',
        creationPerson:item ? item.creationPerson : '',
        creationTime:item.creationTime ? item.creationTime : ''
      })
    })
    //导出表头设计
    let head = {
      id:'序号',
      cl_cph: '车牌号',
      blacklistCause: '黑名单原因',
      startDateTime: '黑名单开始时间',
      endDateTime:'黑名单结束时间',
      black_state:'状态',
      creationPerson:'创建人',
      creationTime:'创建时间'
    }
    //表头数据切换
    const list = exportData.map(item => {
      const obj = {}
      for (const k in item) {
        if (head[k]) {
          obj[head[k]] = item[k]
        }
      }
      return obj
    })
    // 创建工作表
    const data = XLSX.utils.json_to_sheet(list)
    // 创建工作簿
    const wb = XLSX.utils.book_new()
    // 将工作表放入工作簿中
    XLSX.utils.book_append_sheet(wb, data, 'data')
    // 生成文件并下载
    XLSX.writeFile(wb, '黑名单.xlsx')


}

</script>

<style scoped>
/* 面包屑字体颜色更改 */

.breadcrumbColor >>> .el-breadcrumb__inner {
  color: #000;
}
/* 内部header */

.inside-header {
  height: 20px;
  display: flex;
  justify-content: left;
  align-items: flex-start;
  background:#f2f4f5
}
/* 实心按钮背景样式 */

.sele-but {
  background: #3780b9;
  border: 0px;
  border-radius: 2px;
  color: white;
}
/* 空心按钮样式 */

.empty-but {
  border: 1px solid #3780b9;
  color: #3780b9;
}
/*新增按钮样式*/
.add-but {
  background: #dde5fe;
  color: #3780b9;
}
/*照片弹窗及图片样式*/
.photoImg{
  vertical-align: middle;width:500px;height:400px;margin:auto
}
.photoDiv{
  width:100%;display:flex
}
</style>
